//
//  RefreshProductListViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/4/21.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "RefreshProductListViewController.h"
#import "HomepageCollectionViewCell.h"
#import "CommodityDetailsTableViewController.h"

#define HomepageCell  @"HomepageCollectionViewCell"

@interface RefreshProductListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,strong)UICollectionView*collectionView;
@property(nonatomic,strong)NSMutableArray *allDatas;

@property(nonatomic,assign)NSInteger pages;   //第几页

@end

@implementation RefreshProductListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.allDatas = [NSMutableArray array];
    self.view.backgroundColor=[UIColor whiteColor];
    self.pages = 1;
    [self getDatas];
    [self makeNaviButton];
    [self makeView];

//    [self headerRereshing];
    
//    [self addHeader];
//    [self addFooter];
}

#pragma mark---------导航栏

-(void)makeNaviButton{
    self.view.backgroundColor = [UIColor blackColor];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem*item=[[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem=item;
}

#pragma mark 返回事件
-(void)comeBack{
    //    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 获取数据

-(void)getDatas{
 // http://viprunningonline.com/api/index.php?main_page=advanced_search_result
    
//    NSString*urlStr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
//    NSString*pages=[NSString stringWithFormat:@"%d",self.pages];
    NSDictionary*params=@{@"main_page":@"advanced_search_result",@"keyword":self.keywordStr,@"page":[NSString stringWithFormat:@"%ld",(long)self.pages]};
    
//    HttpManager*manager=[[HttpManager alloc]init];
//    [manager getDataFromNetworkNOHUDWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
//        NSLog(@"%@",data);
//        
//        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
//        NSLog(@"%@",number);
//        
//        if ([number isEqualToString:@"1"]) {
//        
//           [self.allDatas addObjectsFromArray:data[@"data"][@"products_list"]];
//        
//        }else{
//        
//            [JRToast showWithText:data[@"status_message"]];
//        }
//        

        // 结束刷新
//        [self.collectionView reloadData];
//        [self.collectionView headerEndRefreshing];
//        [self.collectionView footerEndRefreshing];
//    }];
    [self allDataRequest:params withTitle:nil];

    
    
}
- (void)allDataRequest:(NSDictionary *) paramss withTitle:(NSString *)titleString
{
    NSString*urlStrr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    HttpManager*managerr=[[HttpManager alloc]init];
    [managerr getDataFromNetworkWithUrl:urlStrr parameters:paramss compliation:^(id data, NSError *error) {
        
        [self endRefresh];
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            
            if ([data[@"data"] count] <= 0) {
                [JRToast showWithText:data[@"No data"] duration:2.0];
                return ;
            }
            
            if (self.pages <= [data[@"data"][@"total_pages"] intValue]) {
                [self.allDatas addObjectsFromArray:data[@"data"][@"products_list"] ];
                [self.collectionView reloadData];
                
            }else{
                [JRToast showWithText:@"finsh download data" duration:2.0];
            }
            
        }else{
            [JRToast showWithText:data[@"status_message"] duration:2.0];
        }
        
    }];
}

-(void)makeView{
    
    self.title=@"THE SEARCH RESULTS";
    
    UICollectionViewFlowLayout*flowLayout=[[UICollectionViewFlowLayout alloc]init];
    //    flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
    flowLayout.minimumLineSpacing=10;
    flowLayout.minimumInteritemSpacing=0;
    flowLayout.itemSize=CGSizeMake(ACTUAL_WIDTH(175), ACTUAL_HEIGHT(240));
    flowLayout.sectionInset=UIEdgeInsetsMake(ACTUAL_HEIGHT(0), ACTUAL_WIDTH(8), ACTUAL_HEIGHT(0), ACTUAL_WIDTH(8));
    
    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, ACTUAL_HEIGHT(0), KScreenWidth,ACTUAL_HEIGHT(700)) collectionViewLayout:flowLayout];
    _collectionView.showsHorizontalScrollIndicator=NO;
    _collectionView.showsVerticalScrollIndicator=NO;
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.scrollEnabled=YES;
    [_collectionView registerNib:[UINib nibWithNibName:HomepageCell bundle:nil] forCellWithReuseIdentifier:HomepageCell];
    _collectionView.backgroundColor=[UIColor whiteColor];
    self.collectionView=_collectionView;
    
    [self.view addSubview:_collectionView];
    
    
    __unsafe_unretained typeof(self) vc = self;
    [self.collectionView addHeaderWithCallback:^{
        vc.pages = 1;
        [vc.allDatas removeAllObjects];
        [vc getDatas];
        [vc.collectionView reloadData];
    }];
    
    [self.collectionView addFooterWithCallback:^{
        vc.pages ++ ;
        [vc getDatas];
    }];

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.top).offset(0);
        make.left.mas_equalTo(self.view.left).offset(0);
        make.right.mas_equalTo(self.view.right).offset(0);
        make.bottom.mas_equalTo(self.view.bottom).offset(0);
        
    }];


}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.allDatas.count;
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomepageCollectionViewCell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:HomepageCell forIndexPath:indexPath];
    UIImageView *imageView=[cell viewWithTag:1];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.allDatas[indexPath.item][@"products_image"]] placeholderImage:nil];
    
    UILabel *label1=[cell viewWithTag:2];
    label1.text=self.allDatas[indexPath.item][@"products_name"];
    
    UILabel *label2=[cell viewWithTag:3];
    label2.text=self.allDatas[indexPath.item][@"products_price"];
    
    //    cell.backgroundColor=[UIColor redColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CommodityDetailsTableViewController *vc=[[CommodityDetailsTableViewController alloc]init];
    vc.idStr=self.allDatas[indexPath.item][@"products_id"];
    vc.imgUrlStr = self.allDatas[indexPath.item][@"products_image"];
    [self.navigationController pushViewController:vc animated:YES];
}

//- (void)addHeader
//{
//       __unsafe_unretained typeof(self) vc = self;
//    // 添加下拉刷新头部控件
//    [self.collectionView addHeaderWithCallback:^{
////        vc.pages=0;
////        vc.allDatas=[NSMutableArray array];
//
//        [vc getDatas];
//        
//    } dateKey:@"collection"];
//    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
//    
//#warning 自动刷新(一进入程序就下拉刷新)
//    [self.collectionView headerBeginRefreshing];
//}
//
//- (void)addFooter
//{
//    __unsafe_unretained typeof(self) vc = self;
//    // 添加上拉刷新尾部控件
//    [self.collectionView addFooterWithCallback:^{
//        
//        self.pages++;
//        
//        // 进入刷新状态就会回调这个Block
//        [self getDatas];
//        
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        
//    
//    }];
//}


#pragma mark - endRefresh
- (void)endRefresh{
    
    [self.collectionView headerEndRefreshing];
    [self.collectionView footerEndRefreshing];
}

- (BOOL)slideNavigationControllerShouldDisplayRightMenu
{
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
